/**
 * 简化版API测试脚本
 * 专门测试CreateTokenForm表单对应的后端接口
 */

import axios from 'axios';
import { CreateTokenDto } from '../types/api';

// 配置
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:7172/api';

// 测试数据集合
const getTestData = (): CreateTokenDto[] => [
  // 基础测试
  {
    name: 'Test Token',
    symbol: 'TEST',
    decimals: 9,
    supply: '1000000',
    description: '基础测试代币',
    creator: '11111111111111111111111111111112',
    enablePrettyAddress: false,
    revokeUpdateAuthority: false,
    revokeFreezeAuthority: false,
    revokeMintAuthority: false,
  },
  
  // 靓号地址测试
  {
    name: 'Pretty Token',
    symbol: 'PRETTY',
    decimals: 6,
    supply: '500000',
    description: '靓号地址测试代币',
    creator: '11111111111111111111111111111112',
    enablePrettyAddress: true,
    prettyPrefix: 'ABC',
    prettySuffix: '888',
    caseSensitive: false,
    threads: 2,
    revokeUpdateAuthority: false,
    revokeFreezeAuthority: false,
    revokeMintAuthority: false,
  },
  
  // 完整功能测试
  {
    name: 'Full Feature Token',
    symbol: 'FULL',
    decimals: 8,
    supply: '2000000',
    description: '完整功能测试代币',
    image: 'https://example.com/logo.png',
    creator: '11111111111111111111111111111112',
    enablePrettyAddress: true,
    prettyPrefix: 'FULL',
    prettySuffix: '999',
    caseSensitive: true,
    threads: 4,
    website: 'https://c4pad.com',
    twitter: 'https://twitter.com/example',
    telegram: 'https://t.me/example',
    discord: 'https://discord.gg/example',
    revokeUpdateAuthority: true,
    revokeFreezeAuthority: true,
    revokeMintAuthority: false,
  },
];

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  cyan: '\x1b[36m',
};

function colorLog(color: keyof typeof colors, message: string): void {
  console.log(`${colors[color]}${message}${colors.reset}`);
}

// HTTP客户端
const client = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
});

// 健康检查
async function checkHealth(): Promise<boolean> {
  try {
    colorLog('blue', '🔍 检查后端服务状态...');
    const response = await client.get('/health');
    
    if (response.status === 200) {
      colorLog('green', `✅ 后端服务正常 (${API_BASE_URL})`);
      return true;
    }
    
    colorLog('red', `❌ 后端服务异常: ${response.status}`);
    return false;
  } catch (error) {
    colorLog('red', `❌ 无法连接后端服务: ${error}`);
    return false;
  }
}

// 测试靓号地址估算
async function testPrettyAddressEstimate(): Promise<void> {
  try {
    colorLog('cyan', '🧪 测试靓号地址难度估算...');
    
    const params = new URLSearchParams({
      prefix: 'ABC',
      suffix: '888',
      caseSensitive: 'false',
      threads: '2',
    });
    
    const response = await client.get(`/pretty-address/estimate?${params}`);
    
    if (response.data.success) {
      colorLog('green', '✅ 靓号地址估算接口正常');
      console.log('   估算结果:', response.data.data);
    } else {
      colorLog('yellow', '⚠️ 靓号地址估算返回失败');
    }
  } catch {
    colorLog('yellow', '⚠️ 靓号地址估算接口不可用');
  }
}

// 测试代币创建
async function testTokenCreation(testData: CreateTokenDto, index: number): Promise<boolean> {
  try {
    colorLog('cyan', `\n🧪 测试 ${index + 1}: ${testData.name} (${testData.symbol})`);
    console.log('📝 测试数据:', JSON.stringify(testData, null, 2));
    
    const startTime = Date.now();
    const response = await client.post('/api/tokens', testData);
    const duration = Date.now() - startTime;
    
    if (response.status >= 200 && response.status < 300) {
      if (response.data.success) {
        colorLog('green', `✅ 测试通过 (${duration}ms)`);
        console.log('📋 返回数据:', JSON.stringify(response.data, null, 2));
        return true;
      } else {
        colorLog('red', `❌ 接口返回失败: ${response.data.message}`);
        return false;
      }
    } else {
      colorLog('red', `❌ HTTP错误: ${response.status}`);
      return false;
    }
  } catch (error) {
    if (axios.isAxiosError(error)) {
      colorLog('red', `❌ 请求失败: ${error.response?.data?.message || error.message}`);
      if (error.response?.data) {
        console.log('错误详情:', JSON.stringify(error.response.data, null, 2));
      }
    } else {
      colorLog('red', `❌ 未知错误: ${error}`);
    }
    return false;
  }
}

// 主测试函数
async function runApiTests(): Promise<void> {
  colorLog('blue', '🚀 开始API接口测试');
  colorLog('blue', '='.repeat(50));
  
  // 健康检查
  const isHealthy = await checkHealth();
  if (!isHealthy) {
    colorLog('red', '❌ 后端服务不可用，跳过测试');
    return;
  }
  
  // 测试靓号地址估算
  await testPrettyAddressEstimate();
  
  // 获取测试数据
  const testDataList = getTestData();
  let passedTests = 0;
  
  colorLog('blue', '\n🧪 开始代币创建接口测试...');
  
  // 逐个执行测试
  for (let i = 0; i < testDataList.length; i++) {
    const testData = testDataList[i];
    const success = await testTokenCreation(testData, i);
    
    if (success) {
      passedTests++;
    }
    
    // 测试间隔
    if (i < testDataList.length - 1) {
      await new Promise(resolve => setTimeout(resolve, 2000));
    }
  }
  
  // 输出结果
  colorLog('blue', '\n📊 测试结果汇总');
  colorLog('blue', '='.repeat(30));
  console.log(`总测试数: ${testDataList.length}`);
  console.log(`通过: ${passedTests}`);
  console.log(`失败: ${testDataList.length - passedTests}`);
  console.log(`成功率: ${((passedTests / testDataList.length) * 100).toFixed(1)}%`);
  
  if (passedTests === testDataList.length) {
    colorLog('green', '\n🎉 所有测试通过！');
  } else {
    colorLog('yellow', '\n⚠️ 部分测试失败，请检查日志');
  }
}

// 如果直接运行此文件
if (require.main === module) {
  runApiTests().catch(error => {
    colorLog('red', `测试执行出错: ${error}`);
    process.exit(1);
  });
}

export { runApiTests };
